<?php

namespace app\client\controller\subject;

use app\common\controller\Frontend;
use app\common\model\banxi\learn\LearnSkRecord as LearnSkRecordModel;
use app\common\model\banxi\learn\LearnSubjectQuestionAnswerRecord;
use app\common\model\banxi\learn\LearnSubjectQuestionRecord;
use app\common\model\banxi\student\Student;
use app\common\model\banxi\student\StudentSubjectTeachCollect;
use app\common\model\banxi\subject\Subject as SubjectModel;
use app\common\model\banxi\subject\SubjectCourseDict;
use app\common\model\banxi\subject\SubjectGrade;
use app\common\model\banxi\subject\SubjectKnowledge;
use app\common\model\banxi\subject\SubjectQuestion;
use app\common\model\banxi\subject\SubjectTeach;
use app\common\model\banxi\subject\SubjectTeachChapter;
use app\common\model\banxi\trainer\TrainerSubjectNote;
use app\common\model\banxi\student\StudentLearnSubjectRecord;
use app\common\model\banxi\student\StudentLearnSubjectDuration;
use app\common\model\banxi\student\StudentLearnSubjectFeedback;

/*
 * 全科课程
 * */
class Subject extends Frontend
{
    protected array $noNeedLogin = [];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }


    /*
     * 全科教材
     * */
    public function dict()
    {
        $SubjectCourseDictMoldel = new SubjectCourseDict();
        $list = $SubjectCourseDictMoldel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科教材'), $list);
    }

    /*
     * 全科年级
     * */
    public function grade()
    {
        $SubjectGradeMoldel = new SubjectGrade();
        $list = $SubjectGradeMoldel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科年级'), $list);
    }

    /*
     * 全科科目
     * */
    public function subject()
    {
        $SubjectModel = new SubjectModel();
        $list = $SubjectModel->where(['del'=>0])->order('sortNum', 'desc')->select();

        $this->ok(__('全科科目'), $list);
    }

    /*
     * 课程列表
     * */
    public function courseList()
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $param['query']['EQ_status'] = 1;
        //查询条件解析
        $where = get_query($param);

        //获取分页数据
        $pageParams = get_page_params($param);

        $SubjectTeachModel = new SubjectTeach();
        $list = $SubjectTeachModel->where($where)
            ->with(['subject','gradeInfo','courseDictInfo'])
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                $item['chapterNum'] = SubjectTeachChapter::where(['subjectTeachId'=>$item['id']])->count();
                $item['chapterNum'] = SubjectTeachChapter::where(['subjectTeachId'=>$item['id']])->count();
            });
        $this->ok('操作成功', result_row($list));
    }

    /*
     * 知识点
     * */
    public function knowledge()
    {

        $subjectId = $this->request->get('subjectId',0);
        $subjectGradeId = $this->request->get('subjectGradeId',0);

        $where['del'] = 0;
        $where['pid'] = 0;
        if ($subjectId){
            $where['subjectId'] = $subjectId;
        }
        if ($subjectGradeId){
            $where['subjectGradeId'] = $subjectGradeId;
        }
        $SubjectKnowledgeModel = new SubjectKnowledge();
        $list = $SubjectKnowledgeModel->where($where)
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['children'] = $SubjectKnowledgeModel->where('pid', $value['id'])->order('sortNum','asc')->select();
            }
        }
        $this->ok('操作成功', $list);
    }

    /*
     * 课程详情
     * */
    public function getCourseDetail()
    {
        $id = $this->request->get('id',0);

        $SubjectTeachModel = new SubjectTeach();
        $info = $SubjectTeachModel
            ->where(['id'=>$id])
            ->find();
        if (!$info){
            $this->fail('课程不存在');
        }

        $this->ok('操作成功', $info);
    }

    /*
     * 课程章节
     * */
    public function courseChapter()
    {
        $subjectId = $this->request->get('subjectTeachId',0);
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $list = $SubjectTeachChapterModel
            ->where(['subjectTeachId'=>$subjectId,'del'=>0,'status'=>1])
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            $StudentLearnSubjectDurationModel = new StudentLearnSubjectDuration();
            foreach ($list as $key => $value) {
                $list[$key]['attachment'] = json_decode($value['attachment'],true);
                //获取视频已播放时长
                $duration = $StudentLearnSubjectDurationModel
                    ->where(['subjectTeachChapterId'=>$value['id'],'studentId'=>$this->auth->id])
                    ->find();
                $list[$key]['duration'] = $duration ? $duration['duration'] : 0;

                $list[$key]['isCollect'] = StudentSubjectTeachCollect::where(['subjectTeachChapterId'=>$value['id'],'studentId'=>$this->auth->id])->count();

            }
        }
        $this->ok('课程章节', $list);
    }

    /*
     * 章节题目
     * */
    public function chapterQuestion()
    {
        $subjectChapterId = $this->request->get('subjectChapterId',0);
        $type = $this->request->get('type',1);//1=例题学习;2=随堂联系;
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
//            $this->fail('章节不存在');
            $this->ok('章节题目', true);
        }
        if ($type == 1){
            $question_ids_arr = explode(',',$chapter['beforeClassQuestion']);
        }elseif ($type == 2){
            $question_ids_arr = explode(',',$chapter['inClassQuestion']);
        }
        if (!$question_ids_arr){
            $this->ok('章节题目', true);
        }
        $SubjectQuestionModel = new SubjectQuestion();
        $list = $SubjectQuestionModel
            ->where(['del'=>0,'status'=>1])
            ->whereIn('id',$question_ids_arr)
            ->order('sortNum','asc')
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['option'] = json_decode($value['option'],true);
                $list[$key]['answer'] = json_decode($value['answer'],true);
            }
        }
        $this->ok('章节题目', $list);
    }

    /*
     * 章节知识点
     * */
    public function chapterKnowledge()
    {
        $subjectChapterId = $this->request->get('subjectChapterId',0);
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'del'=>0,'status'=>1])
            ->find();
        if (!$chapter){
//            $this->fail('章节不存在');
            $this->ok('章节知识点', true);
        }
        $SubjectKnowledgeModel = new SubjectKnowledge();
        $knowledge = $SubjectKnowledgeModel
            ->where(['del'=>0])
            ->find();
        $this->ok('章节知识点', $knowledge);
    }


    /*
     * 开始学习
     * */
    public function startLearn()
    {
        $subjectChapterId = $this->request->post('subjectChapterId',0);
        $StudentLearnSubjectRecordModel = new StudentLearnSubjectRecord();
        $user = $this->auth->getUserInfo();

        $record = $StudentLearnSubjectRecordModel
            ->where(['studentId'=>$user['id'],'subjectTeachChapterId'=>$subjectChapterId])
            ->find();
        //已有记录直接返回记录id
        if ($record){
            $this->ok('操作成功', $record['id']);
        }
        $SubjectTeachChapterModel = new SubjectTeachChapter();
        $chapter = $SubjectTeachChapterModel
            ->where(['id'=>$subjectChapterId,'status'=>1])
            ->find();
        if (!$chapter){
            $this->fail('课程章节不存在');
        }
        $SubjectTeachModel = new SubjectTeach();
        $subject_teach = $SubjectTeachModel
            ->where(['id'=>$chapter['subjectTeachId']])
            ->find();
        if (!$subject_teach){
            $this->fail('课程不存在');
        }

        //创建学习记录
        $data = [
            'studentId' => $user['id'],
            'studentOrgId' => $user['organizationId'],
            'subjectId' => $subject_teach['subjectId'],
            'subjectGradeId' => $subject_teach['subjectGradeId'],
            'subjectTeachId' => $subject_teach['id'],
            'subjectTeachChapterId' => $subjectChapterId,
            'name' => $subject_teach['name']
        ];

        $record = $StudentLearnSubjectRecordModel->create($data);
        $this->ok('操作成功', $record['id']);
    }

    /*
     * 更新学习时长和进度
     * */
    public function updateDuration()
    {
        $id = $this->request->post('id',0);

        $duration = $this->request->post('duration',0);
        $videoDuration = $this->request->post('videoDuration',0);
        $LearningProgress = $this->request->post('LearningProgress',0);

        $user = $this->auth->getUserInfo();
        $StudentLearnSubjectRecordModel = new StudentLearnSubjectRecord();
        $record = $StudentLearnSubjectRecordModel
            ->where(['studentId'=>$user['id'],'id'=>$id])
            ->find();
        if (!$record){
            $this->fail('学习记录不存在');
        }
        if ($duration) $record->duration = $record->duration + $duration;
        if ($videoDuration) $record->videoDuration = $videoDuration;
        if ($LearningProgress) $record->learningProgress = $LearningProgress;
        $record->save();
        $this->ok('操作成功');
    }

    /*
     * 提交反馈
     * */
    public function feedback()
    {
        $subjectTeachId = $this->request->post('subjectTeachId',0);
        $subjectChapterId = $this->request->post('subjectChapterId',0);
        $type = $this->request->post('type',0);
        $content = $this->request->post('content','');

        if (!$content){
            $this->fail('请填写反馈内容');
        }
        $user = $this->auth->getUserInfo();
        $StudentLearnSubjectFeedbackModel = new StudentLearnSubjectFeedback();
        $data = [
            'subjectTeachId' => $subjectTeachId,
            'subjectTeachChapterId' => $subjectChapterId,
            'studentId' => $user['id'],
            'studentOrgId' => $user['organizationId'],
            'type' => $type,
            'content' => $content
        ];
        $StudentLearnSubjectFeedbackModel->create($data);

        $this->ok('操作成功');
    }

    /*
     * 分页-课后作业
     * */
    public function listHomeworkPage()
    {
        $limit = $this->request->post('limit', 20);
        $index = $this->request->post('index', 1);
        $searchText = $this->request->get('searchText', '');

        $user = $this->auth->getUserInfo();
        $LearnSkRecordModel = new LearnSkRecordModel();

        $where = [];
        $where[] = ['studentId', '=', $user['id']];
//        $where[] = ['isEnd', '=', 1];
        $where[] = ['afterClassQuestion', '<>', ''];
//        var_dump($where);
        $list = $LearnSkRecordModel->
            with(['trainerInfo'=> function ($query) {
                $query->field('id,name');
            },'courseAppointment'=> function ($query) {
            $query->field('id,date,startTime,endTime,courseName');
            },])
            ->where($where)
            ->order('id', 'desc')
            ->paginate([
                'page' => $index,
                'list_rows' => $limit,
            ]);
        if ($list){
            $LearnSubjectQuestionRecordModel = new LearnSubjectQuestionRecord();
            foreach ($list as $kek=>$value){
                $questionRecord = $LearnSubjectQuestionRecordModel
                    ->where(['skRecordId'=>$value['id'],'exerciseType'=>3])
                    ->find();
                $list[$kek]['questionRecordId'] = $questionRecord ? $questionRecord['id'] : 0;
            }
        }
        $this->ok('操作成功', result_row($list));
    }

    /*
     * 课后作业习题
     * */
    public function homeworkQuestion()
    {
        $skRecordId = $this->request->get('skRecordId',0);

        $LearnSkRecordModel = new LearnSkRecordModel();
        // 获取学习报告数据
        $LearnSkRecord = $LearnSkRecordModel->find($skRecordId);
        if (!$LearnSkRecord){
            $this->fail('学习记录不存在');
        }
        if (!$LearnSkRecord['afterClassQuestion']){
            $this->ok('操作成功', []);
        }
        //获取学生答题记录
        $afterClassQuestionIdsArr = explode(',',$LearnSkRecord['afterClassQuestion']);
        $SubjectQuestionModel = new SubjectQuestion();
        $QuestionList = $SubjectQuestionModel
            ->where(['status'=>1])
            ->whereIn('id',$afterClassQuestionIdsArr)
            ->select();

        $this->ok('操作成功', $QuestionList);
    }

    /*
     * 分页-学习记录列表
     * */
    public function listLearnRecordPage()
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        $studentId = $this->auth->id;
        $param['query']['EQ_studentId'] = $studentId;
        $where = get_query($param);

        //获取分页数据
        $pageParams = get_page_params($param);


        $studentId = $this->auth->id;
        $StudentLearnSubjectRecordModel = new StudentLearnSubjectRecord();

//        var_dump($where);
        $list = $StudentLearnSubjectRecordModel
            ->where($where)
            ->order('id', 'desc')
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ]);
        if ($list)
        {
            $SubjectTeachModel = new SubjectTeach();
            $subjectTeachChapterMode = new SubjectTeachChapter();
            foreach ($list as $k=>$v)
            {
                $subjectTeach = $SubjectTeachModel->field('id,name,showImage')->find($v['subjectTeachId']);
                $subjectTeachChapter = $subjectTeachChapterMode->field('id,name')->find($v['subjectTeachChapterId']);
                $list[$k]['subjectTeach'] = $subjectTeach ? $subjectTeach : [];
                $list[$k]['subjectTeachChapter'] = $subjectTeachChapter ? $subjectTeachChapter : [];
            }
        }
        $this->ok('操作成功', result_row($list));
    }

}